package com.mtung.concurrent.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 卖票
 *
 * @author zhenguo.yao
 * @date 2020/12/28
 */
public class TicketsThread implements Runnable {

    /**
     * 车票的总量
     */
    private Integer count = 100;

    private Lock lock = new ReentrantLock();

    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();


    @Override
    public void run() {
        while (count > 0) {
//            ticketsSync();
            ticketsLock();
        }
    }

    private synchronized void ticketsSync() {
        try {
            Thread.sleep(30);
        } catch (Exception e) {
        }
        if (count > 0) {
            System.out.println(Thread.currentThread().getName() + "正在卖第" + (100 - count + 1) + "张票");
            count--;
        }
    }

    private void ticketsLock() {
        try{
            if(lock.tryLock()){
                Thread.sleep(30);
                if (count > 0) {
                    System.out.println(Thread.currentThread().getName() + "正在卖第" + (100 - count + 1) + "张票");
                    count--;
                }
                lock.unlock();
            }
        }catch (Exception e){

        }
    }


    public static void main(String[] args) {
        TicketsThread ticketsThread = new TicketsThread();
        new Thread(ticketsThread, "窗口1").start();
        new Thread(ticketsThread, "窗口2").start();
    }
}
